package gov.pbc.gx.nn.pz.impl;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import gov.pbc.gx.nn.pz.dao.ZzpzDao;
import gov.pbc.gx.nn.pz.entity.Account;
import gov.pbc.gx.nn.pz.entity.HcXjpz;
import gov.pbc.gx.nn.pz.entity.HcZhglxx;
import gov.pbc.gx.nn.pz.entity.HcZzpz;
import gov.pbc.gx.nn.pz.entity.HcpzXY;
import gov.pbc.gx.nn.pz.entity.PzFont;

import javax.annotation.Resource;
import javax.imageio.ImageIO;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.bstek.bdf2.core.business.IUser;
import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.bdf2.core.exception.NoneLoginException;
import com.bstek.dorado.annotation.DataProvider;
import com.bstek.dorado.annotation.DataResolver;
import com.bstek.dorado.annotation.Expose;
import com.bstek.dorado.data.variant.Record;
import com.bstek.dorado.web.DoradoContext;

/**
 * 
 * @author jack.zhao 本类主要实现zzpz业务逻辑的操作
 * 
 */

@Component("zzpzPR")
public class ZzpzPR {

	private static final Integer PZ_CODE_ = 2;
	private static final Integer Font_Size = 16;
	@Resource
	@Autowired
	private ZzpzDao zzpzDao;

	@Transactional
	@DataProvider
	public Record getZzpzs() {
		try {
			IUser loginuser = ContextHolder.getLoginUser();
			if (loginuser == null)
				return null;
			if (loginuser.getDepts() == null || loginuser.getDepts().size() <= 0)
				return null;
			Record record = new Record();
			record.put("pzdate", new Date());
			ArrayList<HcZzpz> lists = (ArrayList<HcZzpz>) zzpzDao.getMuByDeptName();
			if (lists.isEmpty()) {
				HcZzpz e = new HcZzpz();
				e.setPzDate(new Date());
				e.setPzTemplate("新建模板");
				e.setIsSign(1);
				lists.add(e);
				record.put("zzpz", lists);
			} else {
				lists.get(0).setPzDate(new Date());
				record.put("zzpz", lists);
			}

			List<HcpzXY> xjpzXYs = zzpzDao.getHcPzXYs(PZ_CODE_);
			if (xjpzXYs != null && !xjpzXYs.isEmpty()) {
				record.put("pys", xjpzXYs);
			} else {

				xjpzXYs = new ArrayList<HcpzXY>();
				HcpzXY xjpzXY = new HcpzXY();
				xjpzXY.setProperty("页边距", 50, 50, Font_Size);
				xjpzXYs.add(xjpzXY);

				xjpzXY = new HcpzXY();
				xjpzXY.setId(UUID.randomUUID().toString());
				xjpzXY.setProperty("年", 250, 70, Font_Size);
				xjpzXYs.add(xjpzXY);

				xjpzXY = new HcpzXY();
				xjpzXY.setProperty("月", 330, 70, Font_Size);
				xjpzXYs.add(xjpzXY);

				xjpzXY = new HcpzXY();
				xjpzXY.setProperty("日", 390, 70, Font_Size);
				xjpzXYs.add(xjpzXY);

				// xjpzXY = new HcpzXY();
				// xjpzXY.setProperty("流水号", 560, 70);
				// xjpzXYs.add(xjpzXY);

				xjpzXY = new HcpzXY();
				xjpzXY.setProperty("付款人名称", 110, 110, Font_Size);
				xjpzXYs.add(xjpzXY);

				xjpzXY = new HcpzXY();
				xjpzXY.setProperty("付款人帐号", 110, 165, Font_Size);
				xjpzXYs.add(xjpzXY);

				xjpzXY = new HcpzXY();
				xjpzXY.setProperty("付款人开户银行", 110, 222, Font_Size);
				xjpzXYs.add(xjpzXY);

				// 下面是收款的内容
				xjpzXY = new HcpzXY();
				xjpzXY.setProperty("收款人名称", 440, 110, Font_Size);
				xjpzXYs.add(xjpzXY);

				xjpzXY = new HcpzXY();
				xjpzXY.setProperty("收款人帐号", 440, 165, Font_Size);
				xjpzXYs.add(xjpzXY);

				xjpzXY = new HcpzXY();
				xjpzXY.setProperty("收款人开户银行", 440, 222, Font_Size);
				xjpzXYs.add(xjpzXY);

				// 附件数量
				xjpzXY = new HcpzXY();
				xjpzXY.setProperty("附件数量", 702, 235, Font_Size);
				xjpzXYs.add(xjpzXY);

				xjpzXY = new HcpzXY();
				xjpzXY.setProperty("大写金额", 115, 273, Font_Size);
				xjpzXYs.add(xjpzXY);

				xjpzXY = new HcpzXY();
				xjpzXY.setProperty("小写金额", 688, 293, Font_Size);
				xjpzXYs.add(xjpzXY);

				xjpzXY = new HcpzXY();
				xjpzXY.setProperty("备注", 70, 345, Font_Size);
				xjpzXYs.add(xjpzXY);

			}

			record.put("pys", xjpzXYs);
			return record;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	private void setImageData(Graphics2D graphics, Map<String, Object> param) {
		try {
			HcZzpz hcZzpz = (HcZzpz) param.get("zzpz");

			Date pzdate = (Date) param.get("pzdate");
			int pyx = (int) Integer.parseInt(param.get("x").toString());
			int pyy = (int) Integer.parseInt(param.get("y").toString());
			String fontzh = param.get("fontzh").toString();
			String fonten = param.get("fonten").toString();
			// int pyx = 0, pyy = 0;
			// x = 0;
			// y = 0;
			// Map<String, Object> pym = (Map<String, Object>) param.get("pym");
			graphics.setBackground(Color.WHITE);
			graphics.setColor(Color.BLACK);

			List<HcpzXY> hcpzxys = (List<HcpzXY>) param.get("pys");
			for (HcpzXY pym : hcpzxys) {
				int fontSize = pym.getFontSize();
				Font zhFont = new Font(fontzh, Font.PLAIN, fontSize);
				Font enFont = new Font(fonten, Font.PLAIN, fontSize);

				graphics.setFont(enFont);
				int x = pym.getX() + pyx;
				int y = pym.getY() + pyy;
				String lable = pym.getLabel();
				if (pzdate != null) {
					Calendar calendar = Calendar.getInstance();
					calendar.setTime(pzdate);
					if (lable.equals("年")) {
						graphics.drawString(String.format("%04d", calendar.get(Calendar.YEAR)), x, y);
					}
					if (lable.equals("月")) {
						graphics.drawString(String.format("%02d", calendar.get(Calendar.MONTH) + 1), x, y);
					}
					if (lable.equals("日")) {
						graphics.drawString(String.format("%02d", calendar.get(Calendar.DATE)), x, y);
					}

				}
				if (hcZzpz != null) {

					if (lable.equals("付款人名称")) {
						if (hcZzpz.getPayName() != null) {
							graphics.setFont(zhFont);
							graphics.drawString(hcZzpz.getPayName(), x, y);
						}
					}
					if (lable.equals("付款人帐号")) {
						if (hcZzpz.getPayAccount() != null) {
							graphics.setFont(zhFont);
							graphics.drawString(hcZzpz.getPayAccount(), x, y);
						}
					}
					if (lable.equals("付款人开户银行")) {
						if (hcZzpz.getPayBank() != null) {
							graphics.setFont(zhFont);
							graphics.drawString(hcZzpz.getPayBank(), x, y);
						}
					}
					// 收款
					if (lable.equals("收款人名称")) {
						if (hcZzpz.getCompanyName() != null) {
							graphics.setFont(zhFont);
							graphics.drawString(hcZzpz.getCompanyName(), x, y);
						}
					}
					if (lable.equals("收款人帐号")) {
						if (hcZzpz.getCompanyAccount() != null) {
							graphics.setFont(zhFont);
							graphics.drawString(hcZzpz.getCompanyAccount(), x, y);
						}
					}
					if (lable.equals("收款人开户银行")) {
						if (hcZzpz.getCompanyBank() != null) {
							graphics.setFont(zhFont);
							graphics.drawString(hcZzpz.getCompanyBank(), x, y);
						}
					}
					// 附件数量
					if (lable.equals("附件数量")) {
						graphics.setFont(enFont);
						if (hcZzpz.getAttachmentCount() != null) {
							graphics.drawString(String.valueOf(hcZzpz.getAttachmentCount()), x, y);
						}
					}
					if (lable.equals("备注")) {
						if (hcZzpz.getBz() != null) {
							graphics.setFont(zhFont);
							String[] strs = hcZzpz.getBz().split("\n");
							for (int i = 0; i < strs.length; i++) {
								graphics.drawString(strs[i], x, y + i * zhFont.getSize());
							}
						}
					}
					if (lable.equals("小写金额")) {
						graphics.setFont(enFont);
						DecimalFormat df = new DecimalFormat(".00");
						char[] chars;
						int endX = x;
						// if (hcZzpz.getIsSign().equals("1")) {
						// chars = ("¥" +
						// df.format(hcZzpz.getAmountNum()).replace(".",
						// "")).toCharArray();
						// } else {
						// chars = df.format(hcZzpz.getAmountNum()).replace(".",
						// "").toCharArray();
						// }
						// for (int i = 0; i < chars.length; i++) {
						// graphics.drawString(chars[chars.length - i - 1] + "",
						// endX - i * 14, y);
						// }
						if (hcZzpz.getAmountNum() != null) {
							if (hcZzpz.getIsSign() == 1) {
								chars = ("¥" + df.format(hcZzpz.getAmountNum()).replace(".", "")).toCharArray();
								for (int i = 0; i < chars.length; i++) {
									graphics.drawString(chars[chars.length - i - 1] + "", endX - i * 14, y);
								}
							}

							if (hcZzpz.getIsSign() == 2) {
								chars = ("HKD" + df.format(hcZzpz.getAmountNum()).replace(".", "")).toCharArray();
								for (int i = 0; i < chars.length; i++) {
									graphics.drawString(chars[chars.length - i - 1] + "", endX - i * 14, y);
								}
							}

							if (hcZzpz.getIsSign() == 3) {
								chars = ("USD" + df.format(hcZzpz.getAmountNum()).replace(".", "")).toCharArray();
								for (int i = 0; i < chars.length; i++) {
									graphics.drawString(chars[chars.length - i - 1] + "", endX - i * 14, y);
								}
							}
							if (hcZzpz.getIsSign() == 4) {
								chars = (df.format(hcZzpz.getAmountNum()).replace(".", "")).toCharArray();
								for (int i = 0; i < chars.length; i++) {
									graphics.drawString(chars[chars.length - i - 1] + "", endX - i * 14, y);
								}
							}
							if (hcZzpz.getIsSign() == 0) {
								chars = (df.format(hcZzpz.getAmountNum()).replace(".", "")).toCharArray();
								for (int i = 0; i < chars.length; i++) {
									graphics.drawString(chars[chars.length - i - 1] + "", endX - i * 14, y);
								}
							}
						}

					}
					if (lable.equals("大写金额")) {
						graphics.setFont(zhFont);
						int rowcount = 20;
						if (hcZzpz.getAmountNum() != null) {
							if (hcZzpz.getAmountZh() != null) {

								if (hcZzpz.getIsSign() == 1) {
									if (hcZzpz.getAmountZh().length() > rowcount) {
										graphics.drawString(hcZzpz.getAmountZh().substring(0, rowcount), x, y);
										graphics.drawString(hcZzpz.getAmountZh().substring(rowcount), x, 20 + y);
									} else {
										graphics.drawString(hcZzpz.getAmountZh(), x, y + 10);
									}
								}
								if (hcZzpz.getIsSign() == 2) {
									if (hcZzpz.getAmountZh().length() > rowcount) {
										graphics.drawString("港币 " + hcZzpz.getAmountZh().substring(0, rowcount), x - 40, y);
										graphics.drawString(hcZzpz.getAmountZh().substring(rowcount), x, 20 + y);
									} else {
										graphics.drawString("港币 " + hcZzpz.getAmountZh(), x - 40, y - 3);
									}
								}
								if (hcZzpz.getIsSign() == 3) {
									if (hcZzpz.getAmountZh().length() > rowcount) {
										graphics.drawString("美元 " + hcZzpz.getAmountZh().substring(0, rowcount), x - 40, y);
										graphics.drawString(hcZzpz.getAmountZh().substring(rowcount), x, 20 + y);
									} else {
										graphics.drawString("美元 " + hcZzpz.getAmountZh(), x - 40, y - 3);
									}
								}

								if (hcZzpz.getIsSign() == 4) {
									if (hcZzpz.getAmountZh().length() > rowcount) {
										graphics.drawString(hcZzpz.getAmountZh().substring(0, rowcount), x, y);
										graphics.drawString(hcZzpz.getAmountZh().substring(rowcount), x, 20 + y);
									} else {
										graphics.drawString(hcZzpz.getAmountZh(), x, y + 10);
									}
								}

								if (hcZzpz.getIsSign() == 0) {
									if (hcZzpz.getAmountZh().length() > rowcount) {
										graphics.drawString(hcZzpz.getAmountZh().substring(0, rowcount), x, y);
										graphics.drawString(hcZzpz.getAmountZh().substring(rowcount), x, 20 + y);
									} else {
										graphics.drawString(hcZzpz.getAmountZh(), x, y + 10);
									}
								}
							}
						}
					}
				}

			}

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	@Expose
	public String getPrintImageAll(Map<String, Object> param) {
		try {
			if (param == null)
				return null;
			IUser loginuser = ContextHolder.getLoginUser();
			if (loginuser == null)
				throw new NoneLoginException("您未登录，请刷新页面后重试！！");
			param.put("x", -27);
			param.put("y", -31);
			BufferedImage imagepz = ImageIO.read(new File(DoradoContext.getCurrent().getServletContext().getRealPath("pz/xjpz.png")));
			Graphics2D graphicspz = (Graphics2D) imagepz.getGraphics();

			setImageData(graphicspz, param);
			// ByteArrayOutputStream bytestreampz=new ByteArrayOutputStream();
			String filename = "pz/temp/all_" + loginuser.getUsername() + ".png";
			FileOutputStream fo = new FileOutputStream(new File(DoradoContext.getCurrent().getServletContext().getRealPath(filename)));
			ImageIO.write(imagepz, "png", fo);
			fo.flush();
			fo.close();
			// String
			// str="data:image/png;base64,"+Base64.encodeBase64String(bytestreampz.toByteArray());
			// System.out.println(str.length()+","+bytestreampz.toByteArray().length);
			return filename;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
	}

	@Expose
	public String getPrintImageData(Map<String, Object> param) {
		try {
			if (param == null)
				return null;
			IUser loginuser = ContextHolder.getLoginUser();
			if (loginuser == null)
				throw new NoneLoginException("您未登录，请刷新页面后重试！！");
			param.put("x", -37);
			param.put("y", -34);
			// 35
			// 34
			BufferedImage imagedata = ImageIO.read(new File(DoradoContext.getCurrent().getServletContext().getRealPath("pz/zzpz.png")));
			// System.out.println(imagepz.getWidth()*1.0/96.0*24.5);
			// BufferedImage imagedata= new BufferedImage(imagepz.getWidth(),
			// imagepz.getHeight(), imagepz.getType());
			Graphics2D graphicsdata = (Graphics2D) imagedata.getGraphics();
			graphicsdata.setBackground(Color.WHITE);

			// 打印背景图片
			graphicsdata.clearRect(0, 0, imagedata.getWidth(), imagedata.getHeight());
			setImageData(graphicsdata, param);
			// ByteArrayOutputStream bytestreampz=new ByteArrayOutputStream();
			String filename = "pz/temp/data_" + loginuser.getUsername() + ".png";
			FileOutputStream fo = new FileOutputStream(new File(DoradoContext.getCurrent().getServletContext().getRealPath(filename)));
			ImageIO.write(imagedata, "png", fo);
			fo.flush();
			fo.close();
			// String
			// str="data:image/png;base64,"+Base64.encodeBase64String(bytestreampz.toByteArray());
			// System.out.println(str.length()+","+bytestreampz.toByteArray().length);
			return filename;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
	}

	@Expose
	public Map<String, Object> getUserInfo() {
		IUser loginuser = ContextHolder.getLoginUser();
		Map<String, Object> userinfo = new HashMap<String, Object>();
		if (loginuser == null) {
			userinfo.put("cname", "");
			userinfo.put("dept", "");
			return userinfo;
		}
		userinfo.put("cname", loginuser.getCname());
		if (loginuser.getDepts() == null || loginuser.getDepts().size() <= 0) {
			userinfo.put("dept", "");
			return userinfo;
		}
		userinfo.put("dept", loginuser.getDepts().get(0).getName());
		return userinfo;
	}

	@DataProvider
	public Collection<HcZzpz> getTypeByGroup() {

		ArrayList<HcZzpz> xjpzs = new ArrayList<HcZzpz>();
		xjpzs = (ArrayList<HcZzpz>) zzpzDao.getOneGroupByType();
		for (int i = 0; i < xjpzs.size(); i++) {
			xjpzs.get(i).setPzDate(new Date());
		}
		return xjpzs;

		// return zzpzDao.getOneGroupByType();

	}

	@DataProvider
	public Collection<HcZzpz> getTepementNameByType(Map<String, Object> param) {
		if (param == null) {
			return null;
		}
		String type = (String) param.get("type");

		ArrayList<HcZzpz> xjpzs = new ArrayList<HcZzpz>();
		xjpzs = (ArrayList<HcZzpz>) zzpzDao.getCoByType(type);
		for (int i = 0; i < xjpzs.size(); i++) {
			xjpzs.get(i).setPzDate(new Date());
		}
		return xjpzs;

		// return zzpzDao.getCoByType(type);
	}

	@Expose
	public HcZzpz ajaxselectOneByTypeAndTemplate(Map<String, Object> param) {
		String type = (String) param.get("type");
		String pztemplate = (String) param.get("pzTemplate");
		if (type == null || pztemplate == null) {
			return null;
		}

		HcZzpz pz = zzpzDao.selectOneByTypeAndTemplate(type, pztemplate);
		pz.setPzDate(new Date());
		return pz;

		// return zzpzDao.selectOneByTypeAndTemplate(type, pztemplate);

	}

	@DataProvider
	public List<Record> getFonts() {
		return zzpzDao.getFonts();
	}

	@DataProvider
	public PzFont getFont() {
		return zzpzDao.getFont(PZ_CODE_);
	}

	@Transactional
	@DataResolver
	public void saveZzpz(HcZzpz hcZzpz) {
		zzpzDao.saveZzpz(hcZzpz);
	}

	@Transactional
	@DataResolver
	public void savepzXY(Collection<HcpzXY> hcpzxys) {
		zzpzDao.saveXjpzXY(hcpzxys);

	}

	@Transactional
	@DataResolver
	public void saveFont(PzFont pzFont) throws Exception {
		zzpzDao.updateFont(pzFont);
	}

	@Expose
	public void deleteTemplateById(String id) {
		if (StringUtils.isEmpty(id)) {
			return;
		}
		zzpzDao.deleteTemplateById(id);
	}

	@Expose
	public Account ajaxActionGetName(Map<String, Object> parameter) {
		String account = (String) parameter.get("account");
		return zzpzDao.getAccountName(account);

	}

	@Expose
	public boolean updateTempalteName(Map<String, Object> parameter) {
		String id = (String) parameter.get("id");
		String pzTemplate = (String) parameter.get("pzTemplate");
		return zzpzDao.updateTemplateNameDao(pzTemplate, id);
	}

	@Expose
	public boolean updateTempalteType(Map<String, Object> parameter) {
		String id = (String) parameter.get("id");
		String type = (String) parameter.get("type");
		return zzpzDao.updateTemplateTypeDao(type, id);
	}

}
